// 个人资料
import {
  Col,
  DatePicker,
  Divider,
  Flex,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  type FormInstance,
} from 'antd';

import FormAuth from '@/components/FormAuth';
import Select from '@/components/NewSelect';
import { findByCodeList, getCountry } from '@/services/login';
import { getOptions, phoneFormatter, validIdNumber } from '@/utils';
import {
  chinaName,
  dataFrommat,
  enName,
  genderOptions,
  idCardPattern,
  passwordPattern,
  pattern,
} from '@/utils/common';
import { useRequest } from 'ahooks';
import { type Gutter } from 'antd/es/grid/row';

import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import { useIntl } from 'umi';
import ChangePhoneModal from './ChangePhoneModal';
const StepOne: React.FC<{
  form: FormInstance<any>;
  gutter?: Gutter | [Gutter, Gutter];
  isCenter?: boolean;
  span?: number;
  required?: boolean;
  needPassWord?: boolean;
}> = ({ form, gutter = [20, 0], isCenter = false, span, required = true, needPassWord }) => {
  const intl = useIntl();
  const [visible, setVisible] = useState(false);

  const phone = Form.useWatch('mobile', form);
  const { data } = useRequest(() => {
    return findByCodeList({
      code: 'residentialStatus',
    });
  });
  const inputRef = useRef();
  const { data: countryList } = useRequest(getCountry);
  const { residentialStatus } = data?.data || {};
  const title = phone
    ? intl.formatMessage({ id: 'login.phone.change' })
    : intl.formatMessage({ id: 'login.phone.change1' });
  return (
    <>
      {!isCenter ? (
        <div className="info_right_form_title">
          {intl.formatMessage(
            { id: 'center.write' },
            { label: intl.formatMessage({ id: 'home.user_info' }).toLowerCase() },
          )}
        </div>
      ) : (
        <div className="info_right_form_sTitle">{intl.formatMessage({ id: 'home.user_info' })}</div>
      )}

      {/* 个人资料 */}
      <Row gutter={gutter}>
        {needPassWord ? (
          <>
            <Col span={12}>
              <Form.Item
                rules={[
                  { required: true },
                  {
                    validator: (_, value) =>
                      new Promise<void>((resolve, reject) => {
                        if (value) {
                          if (passwordPattern.pattern.test(value)) {
                            resolve();
                          } else {
                            reject(new Error(intl.formatMessage({ id: passwordPattern.message })));
                          }
                        } else {
                          reject();
                        }
                      }),
                  },
                ]}
                label={intl.formatMessage({ id: 'home.login_pass' })}
                name="password"
                validateTrigger="onBlur"
              >
                <Input
                  maxLength={12}
                  autoComplete="new-password"
                  placeholder={intl.formatMessage({ id: 'home.login_pass_set' })}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, curValues) => prevValues.password !== curValues.password}
              >
                {({ getFieldValue }) => {
                  const password = getFieldValue('password');
                  return (
                    <Form.Item
                      validateTrigger="onBlur"
                      rules={[
                        { required: true },
                        {
                          validator: (_, value) =>
                            new Promise<void>((resolve, reject) => {
                              if (value) {
                                if (password === value) {
                                  resolve();
                                } else {
                                  reject(
                                    new Error(
                                      intl.formatMessage({ id: 'app.configuration.password_same' }),
                                    ),
                                  );
                                }
                              } else {
                                reject();
                              }
                            }),
                        },
                      ]}
                      label={intl.formatMessage({ id: 'home.login_pass_confirm' })}
                      name="password_confirmation"
                    >
                      <Input
                        maxLength={12}
                        autoComplete="new-password"
                        placeholder={intl.formatMessage({
                          id: 'home.login_pass_confirm_set',
                        })}
                      />
                    </Form.Item>
                  );
                }}
              </Form.Item>
            </Col>
            <Col span={24}>
              <div
                style={{
                  color: '#333',
                  fontWeight: 400,
                  fontSize: 17,
                  marginTop: '-10px',
                }}
              >
                {intl.formatMessage({ id: 'home.login_pass_info' })}
              </div>
              <Divider style={{ margin: '18.5px 0' }} />
            </Col>
          </>
        ) : null}
        <FormAuth
          span={span || 12}
          label={intl.formatMessage({ id: 'home.c_surname' })}
          rules={[{ required: true }, { ...chinaName }]}
          name="firstNameCn"
        >
          <Input maxLength={3} placeholder={intl.formatMessage({ id: 'home.c_surname' })} />
        </FormAuth>
        <FormAuth
          span={span || 12}
          label={intl.formatMessage({ id: 'home.c_name' })}
          rules={[{ required: true }, { ...chinaName }]}
          name="lastNameCn"
        >
          <Input maxLength={3} placeholder={intl.formatMessage({ id: 'home.c_name' })} />
        </FormAuth>
        <FormAuth
          label={intl.formatMessage({ id: 'home.e_surname' })}
          name="firstNameEn"
          span={span || 12}
          rules={[{ required: true }, { ...enName }]}
        >
          <Input maxLength={20} placeholder={intl.formatMessage({ id: 'home.e_surname' })} />
        </FormAuth>
        <FormAuth
          label={intl.formatMessage({ id: 'home.e_name' })}
          name="lastNameEn"
          span={span || 12}
          rules={[{ required: true }, { ...enName }]}
        >
          <Input maxLength={20} placeholder={intl.formatMessage({ id: 'home.e_name' })} />
        </FormAuth>
        {isCenter ? (
          <FormAuth
            span={span || 24}
            rules={[{ required }]}
            label={intl.formatMessage({ id: 'home.gender' })}
            name="sex"
          >
            <Select
              placeholder={intl.formatMessage({ id: 'home.gender' })}
              options={genderOptions}
            />
          </FormAuth>
        ) : (
          <FormAuth
            span={span || 24}
            rules={[{ required }]}
            label={intl.formatMessage({ id: 'home.gender' })}
            name="sex"
          >
            <Radio.Group className="sex_options" options={genderOptions} />
          </FormAuth>
        )}
        {isCenter ? <Col style={{ marginTop: 24 }} span={24} /> : null}
        <FormAuth
          label={intl.formatMessage({ id: 'home.phone' })}
          rules={[{ required }]}
          style={{ cursor: 'pointer' }}
          name="mobile"
          onClick={() => {
            setVisible(true);
          }}
          span={span || 24}
        >
          <InputNumber
            formatter={(value) => {
              return phoneFormatter(value as string);
            }}
            readOnly
            prefix={<div style={{ fontSize: 18 }}>+852</div>}
            style={{ width: '100%' }}
            controls={false}
            suffix={
              <div
                style={{
                  color: '#0270DF',
                  fontSize: 16,
                  cursor: 'pointer',
                  position: 'relative',
                  zIndex: 100,

                  textAlign: 'right',
                }}
              >
                {intl.formatMessage({ id: phone ? 'login.phone.changes' : 'login.get' })}
              </div>
            }
            placeholder={intl.formatMessage({ id: 'home.phone' })}
          />
        </FormAuth>

        <FormAuth
          rules={[{ required }]}
          label={intl.formatMessage({ id: 'home.people' })}
          name="residentialStatus"
          span={span || 24}
        >
          <Select
            placeholder={intl.formatMessage({ id: 'home.people' })}
            options={getOptions(residentialStatus)}
          />
        </FormAuth>
        <FormAuth
          rules={[{ required }]}
          label={intl.formatMessage({ id: 'home.birthday' })}
          name="birthday"
          span={span || 24}
        >
          <DatePicker
            maxDate={dayjs().subtract(18, 'year')}
            minDate={dayjs().subtract(80, 'year')}
            format={dataFrommat}
            placeholder={intl.formatMessage({ id: 'home.birthday' })}
          />
        </FormAuth>
        {/* <FormAuth
          rules={[{ required }]}
          label={intl.formatMessage({ id: 'home.idcard_type' })}
          name="birthday"
          span={span || 24}
        >
          <DatePicker placeholder={intl.formatMessage({ id: 'home.idcard_type' })} />
        </FormAuth> */}
        {isCenter ? (
          <FormAuth
            span={span || 6}
            rules={[{ required }]}
            label={intl.formatMessage({ id: 'home.id_card' })}
            name="cardNumber"
          >
            <Input placeholder={intl.formatMessage({ id: 'home.id_card_exmaple1' })} />
          </FormAuth>
        ) : (
          <>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, curValues) =>
                prevValues.cardNumber2 !== curValues.cardNumber2
              }
            >
              {({ getFieldValue }) => {
                const cardNumber2 = getFieldValue('cardNumber2');

                return (
                  <FormAuth
                    span={18}
                    rules={[
                      { required },
                      {
                        validator: (_, value) =>
                          new Promise<void>((resolve, reject) => {
                            if (value) {
                              if (!cardNumber2) {
                                if (idCardPattern.pattern.test(value)) {
                                  resolve();
                                } else {
                                  reject(
                                    new Error(intl.formatMessage({ id: idCardPattern.message })),
                                  );
                                }
                              } else {
                                if (validIdNumber(`${value}(${cardNumber2})`)) {
                                  resolve();
                                } else {
                                  reject(
                                    new Error(intl.formatMessage({ id: idCardPattern.message })),
                                  );
                                }
                              }
                            } else {
                              reject();
                            }
                          }),
                      },
                    ]}
                    label={intl.formatMessage({ id: 'home.id_card' })}
                    name="cardNumber1"
                    validateTrigger="onBlur"
                  >
                    <Input
                      onChange={(e) => {
                        if (e.target.value.length == 8) {
                          form.setFieldValue('cardNumber1', e.target.value.slice(0, 7));
                          form.setFieldValue('cardNumber2', e.target.value.slice(7, 8));
                          if (inputRef.current) {
                            (inputRef.current as any).focus();
                          }
                        }
                      }}
                      maxLength={8}
                      placeholder={intl.formatMessage({ id: 'home.id_card_exmaple' })}
                    />
                  </FormAuth>
                );
              }}
            </Form.Item>
            <Flex wrap="nowrap" style={{ fontSize: 18, marginTop: 30 }}>
              <FormAuth
                label={intl.formatMessage({ id: 'home.id_card' })}
                span={24}
                labelCol={{ span: 0 }}
                rules={[{ required }, pattern]}
                style={{ width: '145px', margin: '0 auto' }}
                name="cardNumber2"
              >
                <Input
                  ref={inputRef as any}
                  onBlur={() => {
                    form.validateFields(['cardNumber1']);
                  }}
                  style={{ width: '140px', textAlign: 'center' }}
                  addonBefore={<span style={{ marginRight: 20 }}>（</span>}
                  className="idcard_input"
                  addonAfter={<span style={{ marginLeft: 20 }}>）</span>}
                  maxLength={1}
                  minLength={1}
                />
              </FormAuth>
            </Flex>
          </>
        )}

        <FormAuth
          rules={[{ required }]}
          label={intl.formatMessage({ id: 'home.country' })}
          name="nation"
          span={span || 24}
        >
          <Select
            placeholder={intl.formatMessage({ id: 'home.country' })}
            options={getOptions(countryList?.data, 'name', 'id')}
          />
        </FormAuth>
      </Row>
      <ChangePhoneModal
        visible={visible}
        handleCancel={() => {
          setVisible(false);
        }}
        title={title}
        handleOk={(phone: string) => {
          setVisible(false);
          form.setFieldValue('mobile', phone);
        }}
      />
    </>
  );
};

export default StepOne;
